package study.聊天室;

import org.springframework.util.ObjectUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private Socket socket;
    private List<PrintWriter> pws = new ArrayList<>();
    private ExecutorService threatPool = Executors.newFixedThreadPool(4);

    public Server(){
        System.out.println("正在启动服务器");

        try {
            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("服务器启动成功");
    }

    private void start(){
        try {
            while (true){
                System.out.println("等待客户端连接");
                // 服务器准备接收套接字
                // 当双方的套接字连接起来之后，通信准备就完成了
                // 套接字一般是由客户端创建的
                socket = serverSocket.accept();
                System.out.println("客户端连接成功");
                ClientHandler clientHandler = new ClientHandler();
//                Thread t = new Thread(clientHandler);
//                t.start();
                threatPool.execute(clientHandler);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class ClientHandler implements Runnable{
        private String host;

        public ClientHandler() {
            host = socket.getInetAddress().getHostName();
            // socket: addr:要找的服务端ip地址，localport：要找的服务端端口， port：客户端唯一标识
            System.out.println(socket);
        }


        public void run(){
            PrintWriter pw = null;
            int port = 0;
            try {
                // 接收客户端发的消息
                port = socket.getPort();
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader br = new BufferedReader(isr);



                // 要发消息给所有客户端
                OutputStream os = socket.getOutputStream();
                pw = new PrintWriter(os,true);
                synchronized (pws){
                    pws.add(pw);
                    for(PrintWriter p : pws){
                        p.println(port+"上线了");
                    }
                }

                String line;
                //阻塞
                while ((line = br.readLine()) != null){

                    System.out.println(port +"说："+line);
                    sendMessage(line, port);
                }
            } catch (IOException e) {
                System.out.println(port +"客户端异常断开了");;
            }finally {
                synchronized (pws){
                    pws.remove(pw);
                    for (PrintWriter p : pws ){
                        int clientCount = pws.size();
                        p.println(port + "断开了，" + "当前在线人数：" + clientCount);
                    }
                }

            }

        }

        private void sendMessage(String line,int port){
            synchronized (pws){
                for (PrintWriter pw : pws){
                    pw.println(port +"说："+line);
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}

